package main.java.com.lee.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/11
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Semaphore semaphore = new Semaphore(2);
        IntStream.rangeClosed(1, 10).forEach(i->{
            executorService.submit(() -> {
                try {
                    business(semaphore);
                } catch (InterruptedException e) {
                }
            });
        });
        executorService.shutdown();
        while (!executorService.isTerminated()) {

        }
    }

    private static void business(Semaphore semaphore) throws InterruptedException {
        semaphore.acquire(3);
        semaphore.acquireUninterruptibly(3);
        System.out.println(Thread.currentThread().getName() + "获得许可");
        Thread.sleep(5000);
        semaphore.release();
    }
}
